class Image < ActiveRecord::Base

  FILENAME_LENGTH = 10
  DIRECTORY = 'public/images/items'

  belongs_to :grid

  validates_presence_of :filename, :grid_id
  validates_format_of :filename,
      :with => %r{\.(gif|jpg|png)$}i

  def after_save
    File.open(file_path, "wb") { |f| f.write(@file.read) }
  end

  def before_destroy
    File.delete(file_path)
  end

  def url
    '/images/items/' + filename
  end

  def file=(file)
    if file
      @file = file
      extension = file.original_filename.split('.').last
      self.filename = generate_filename + ".#{extension}"
    end
  end

  private

  def file_path
    File.join(DIRECTORY, filename)
  end

  def generate_filename
    chars = 'abcdefghjkmnpqrstuvwxyzABCDEFGHJKLMNOPQRSTUVWXYZ23456789'
    filename = ''
    FILENAME_LENGTH.times { |i| filename << chars[rand(chars.length)] }
    filename
  end

end
